/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect } from 'react';
import { Modal, Form, Input, Row, Col } from 'antd';
import { getSmsCode } from '@/services/setup';
import CaptchaNoRobot from '@/components/Captcha/no-robot';
import { check } from '@/utils/patterns';

const FormItem = Form.Item;

const noop = () => {};

/**
 * 代入库，短信验证弹窗
 *  */
const SmsModal = props => {
  const { form, onOk = noop, onCancel, cm_id, platform, phone, password, submitting } = props;

  const { getFieldDecorator, validateFields, setFieldsValue } = form;

  const handleOk = () => {
    validateFields((err, values) => {
      if (err) return;
      const { code } = values || {};
      onOk({ smsCode: code });
    });
  };

  const getSmsCodeRequest = () =>
    new Promise((resolve, reject) => {
      const { code, message } = check('phone', phone);
      if (code > 0) {
        reject(new Error(message));
        return;
      }
      getSmsCode({ username: phone, complate: platform, password }).then(resolve, reject);
    });

  useEffect(
    () => {
      setFieldsValue({
        phone,
        code: '',
      });
    },
    [phone],
  );

  return (
    <Modal
      confirmLoading={submitting}
      title={`请登录${platform}驿站`}
      width={300}
      visible={!!phone}
      onOk={handleOk}
      onCancel={onCancel}
      okText="登录"
    >
      <Form>
        <FormItem>
          <Row type="flex">
            <Col style={{ flex: 1 }}>
              {getFieldDecorator('phone', {
                initialValue: phone,
                rules: [
                  {
                    required: true,
                    message: '请输入手机号',
                  },
                ],
              })(<Input disabled allowClear placeholder="请输入手机号" />)}
            </Col>
            <Col>
              <CaptchaNoRobot request={getSmsCodeRequest} />
            </Col>
          </Row>
        </FormItem>
        <FormItem>
          {getFieldDecorator('code', {
            rules: [
              {
                required: true,
                message: '请输入短信验证码',
              },
            ],
          })(
            <Input
              disabled={!!cm_id}
              allowClear
              placeholder="请输入短信验证码"
              style={{ width: 250 }}
            />,
          )}
        </FormItem>
      </Form>
    </Modal>
  );
};

export default Form.create()(SmsModal);
